package Servlet;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import dao.UserDao;


@WebServlet("/admin/user")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String opt = request.getParameter("opt");
		if(opt == null || "".equals(opt))
		{
			List<User> users = (new UserDao()).findAll();
			request.setAttribute("users", users);
			opt="user_list";
		}
		else if("add".equals(opt))
		{
			opt="user_a";
		}
		request.getRequestDispatcher("/WEB-INF/pages/admin/"+opt+".jsp").forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		String opt = request.getParameter("opt");
		if(opt == null || "".equals(opt))
			opt="user";
		else if("add".equals(opt))
		{
			String userName = request.getParameter("userName");
			String sex = request.getParameter("sex");
			String phone = request.getParameter("phone");
			String qq = request.getParameter("qq");
			String address = request.getParameter("address");
			User user = new User();
			user.setUserName(userName);
			user.setSex(sex);
			user.setPhone(phone);
			user.setQq(qq);
			user.setAddress(address);
			Random rnd = new Random();
			user.setId(rnd.nextInt());
			new UserDao().add(user);
			opt="user";
		}
		response.sendRedirect(opt);
	}
}
